package com.heima.search.utils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.search.utils.mapper.ApArticleContentMapper;
import com.heima.search.utils.mapper.ApArticleMapper;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
@RunWith(SpringRunner.class)
public class ImportEsData {
    private static final String INDEX_TEMPLATE ="{\n" +
            "      \"properties\" : {\n" +
            "        \"authorId\" : {\n" +
            "          \"type\" : \"integer\"\n" +
            "        },\n" +
            "        \"content\" : {\n" +
            "          \"type\" : \"text\",\n" +
            "          \"analyzer\" : \"ik_smart\"\n" +
            "        },\n" +
            "        \"id\" : {\n" +
            "          \"type\" : \"keyword\"\n" +
            "        },\n" +
            "        \"images\" : {\n" +
            "          \"type\" : \"keyword\"\n" +
            "        },\n" +
            "        \"layout\" : {\n" +
            "          \"type\" : \"short\"\n" +
            "        },\n" +
            "        \"publishTime\" : {\n" +
            "          \"type\" : \"date\"\n" +
            "        },\n" +
            "        \"title\" : {\n" +
            "          \"type\" : \"text\",\n" +
            "          \"analyzer\" : \"ik_smart\"\n" +
            "        }\n" +
            "      }\n" +
            "    }";

    private static final String INDEXNAME="app_info_article";

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Test
    public void importAllData(){
        Boolean isExist = isExist(INDEXNAME);
        if (isExist){
            deleteIndex(INDEXNAME);
        }
        creatIndex(INDEXNAME,INDEX_TEMPLATE);


        List<ApArticle> apArticles = apArticleMapper.loadArticleList();

        BulkRequest bulkRequest = new BulkRequest();
        for (ApArticle apArticle : apArticles) {
            ApArticleContent content = apArticleContentMapper.selectOne(
                    Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId, apArticle.getId())
            );
            // 封装文章数据
            Map<String,Object> map = new HashMap<>();
            map.put("id", String.valueOf(apArticle.getId()));
            map.put("publishTime", apArticle.getPublishTime());
            map.put("layout", apArticle.getLayout());
            map.put("images", apArticle.getImages());
            map.put("authorId", apArticle.getAuthorId());
            map.put("title", apArticle.getTitle());
            map.put("content", content.getContent());

            IndexRequest request = new IndexRequest();
            IndexRequest indexRequest = new IndexRequest(INDEXNAME);
            indexRequest.id(String.valueOf(apArticle.getId())).source(map);
            bulkRequest.add(indexRequest);
        }
        try {
            restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void creatIndex(String indexName,String indexTemplate) {
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        request.mapping(indexTemplate, XContentType.JSON);

        try {
            restHighLevelClient.indices().create(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void deleteIndex(String indexName) {
        DeleteIndexRequest request= new DeleteIndexRequest(indexName);

        try {
            restHighLevelClient.indices().delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Boolean isExist(String indexName) {
        GetIndexRequest request = new GetIndexRequest(indexName);
        boolean exists = false;
        try {
            exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return exists;
    }
}
